package com.ruoyi.recycleshop.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.recycle.domain.*;
import com.ruoyi.recycle.service.*;
import com.ruoyi.recycleshop.vo.DataStatisticsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;

@RestController
@RequestMapping("/homePage")
@Api(tags = "首页")
public class HomePageController extends BaseController {
    @Autowired
    private IRecycleCommodityService commodityService;
    @Autowired
    private IClientUserManagementService clientUserManagementService;
    @Autowired
    private IRecycleOrderService recycleOrderService;
    @Autowired
    private BillRecordService billRecordService;
    @Autowired
    private IShopManagementService shopManagementService;
    @Autowired
    private IHomePageSlideshowService homePageSlideshowService;

    @GetMapping("/dataStatistics")
    @ApiOperation("门店数据统计")
    @ApiImplicitParam(name = "shopId", value = "门店ID")
    public R<DataStatisticsVO> dataStatistics(@RequestParam Long shopId) {
        final LambdaQueryWrapper<ClientUserManagement> wrapper = Wrappers.lambdaQuery(new ClientUserManagement()).eq(ClientUserManagement::getShopId, shopId);
        final List<ClientUserManagement> clients = clientUserManagementService.list(wrapper);
        double carbonReduceSum = 0.00;
        int attractDayRecord = 0;
        Double dailyBonus = 0.00;
        int users = 0;
        Double totalBonus = 0.00;
        final Date currentDate = new Date();
        if (CollUtil.isNotEmpty(clients)) {
            final List<Long> clientIds = clients.stream().map(ClientUserManagement::getId).collect(Collectors.toList());
            final List<RecycleOrder> orders = recycleOrderService.list(Wrappers.lambdaQuery(new RecycleOrder()).in(RecycleOrder::getClientId, clientIds));
            if (CollUtil.isNotEmpty(orders)) {
                final List<String> orderNos = orders.stream().map(RecycleOrder::getRecycleOrderNo).collect(Collectors.toList());
                final List<RecycleCommodity> list = commodityService.list(Wrappers.lambdaQuery(new RecycleCommodity()).in(RecycleCommodity::getOrderId, orderNos));
                carbonReduceSum = list.stream().filter(rc -> Objects.nonNull(rc.getPracticalWeight())).map(RecycleCommodity::getPracticalWeight).mapToDouble(BigDecimal::doubleValue).sum();

            }
        }
        users = clientUserManagementService.count(wrapper);
        attractDayRecord = clientUserManagementService.count(wrapper.like(ClientUserManagement::getCreatedTime, DateUtil.format(new Date(), "yyyy-MM-dd")));
        final List<BillRecord> billRecords = billRecordService.list(Wrappers.lambdaQuery(new BillRecord()).eq(BillRecord::getUserId, shopId)
                .eq(BillRecord::getType, 1)
                .eq(BillRecord::getUserType, 3));
        if (CollUtil.isNotEmpty(billRecords)) {
            totalBonus = billRecords.stream().filter(b -> Objects.nonNull(b.getIncome())).flatMapToDouble(b -> DoubleStream.of(b.getIncome().doubleValue())).sum();
            dailyBonus = billRecords.stream().filter(b -> Objects.nonNull(b.getIncome())).filter(b -> DateUtil.isSameDay(currentDate, b.getCreateTime()))
                    .flatMapToDouble(b -> DoubleStream.of(b.getIncome().doubleValue())).sum();
        }

        return R.ok(new DataStatisticsVO()
                .setAmountUsers(users)
                .setAmountIntegral(totalBonus)
                .setCarbon(carbonReduceSum)
                .setTodayIntegral(dailyBonus.intValue())
                .setTodayUsers(attractDayRecord)
                .setTons(carbonReduceSum / 1000));
    }

    @ApiOperation("获取海报列表")
    @GetMapping("/getPosterList")
    public R<List<HomePageSlideshow>> getPosterList() {
        return R.ok(homePageSlideshowService.list(Wrappers.lambdaQuery(new HomePageSlideshow()).eq(HomePageSlideshow::getType, "5")));

    }

    @ApiOperation("获取默认海报")
    @GetMapping("/getDefaultPoster")
    public R<HomePageSlideshow> getDefaultPoster() {
        final List<HomePageSlideshow> posterList = homePageSlideshowService.list(Wrappers.lambdaQuery(new HomePageSlideshow()).eq(HomePageSlideshow::getType, "5"));
        if (CollUtil.isEmpty(posterList)) {
            return R.ok(new HomePageSlideshow().setType("5"));
        }
        return R.ok(posterList.get(0));
    }


    @ApiOperation("保存推广海报")
    @PostMapping("/savePoster")
    public R<String> savePoster(@RequestBody ShopManagement shopManagement) {
        shopManagementService.updateById(shopManagement);
        return R.ok(shopManagement.getPoster());
    }


}
